package com.legend.security;

/**
 * User: ChuanQi
 * Date: 13-6-13
 * Time: 下午3:58
 * To change this template use File | Settings | File Templates.
 */

import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.wh.beans.ConstVar;
import com.legend.utils.EhCacheUtil;

/*
 * SAX方式用于解析XML文件的解析器
 */
public class PermissionConfig extends DefaultHandler {
	private List<Permission> permissions = null;
	private Permission permission = null;
	private PermissionItem permissionItem = null;
	private List<PermissionItem> items = null;
	private final static String FILENAME = "security/permission.1.0.xml";

	public PermissionConfig() {
		/*
		 * try { parse(FILENAME); } catch (Exception e) { e.printStackTrace(); }
		 */
	}

	/**
	 * 操作权限列表
	 */
	@SuppressWarnings("unchecked")
	public List<PermissionItem> getPermissionItems(String moduleCode)
			throws Exception {
		List<Permission> lst = getPermissions();
		for (Permission p : lst)
			if (moduleCode.equals(p.getModuleCode())) {
				// p.setModuleName("");
				List<PermissionItem> itms = p.getItems();
				Collections.sort(itms, new Comparator<PermissionItem>() {
					@Override
					public int compare(PermissionItem o1, PermissionItem o2) {
						int flag = o1.getSort().compareTo(o2.getSort());
						return flag;
					}
				});
				return itms;
			}
		return null;
	}

	/*
	 * 返回所有权限操作项
	 */
	@SuppressWarnings("unchecked")
	public List<Permission> getPermissions() {
		List<Permission> lst;
		EhCacheUtil cache = EhCacheUtil.getInstance();
		Object obj = cache.get(ConstVar.FEREVER_CACHE, "permission");
		if (obj == null) {
			PermissionConfig parser = new PermissionConfig();
			try {
				parser.parse(FILENAME);
			} catch (Exception e) {
				System.out.println("异常：" + e);
			}
			lst = getPermissions();
		} else {
			lst = (List<Permission>) obj;
		}
		
		
		return lst;
	}

	/*
	 * 用于分析xml文件的方法
	 */
	public void parse(String filename) throws Exception {
		// 实例化用于分析的工厂
		SAXParserFactory factory = SAXParserFactory.newInstance();
		// 实例化分析类
		SAXParser parser = factory.newSAXParser();
		// 得到xml文件对应的路径
		URL confURL = PermissionConfig.class.getClassLoader().getResource(
				filename);
		try {
			parser.parse(confURL.toString(), PermissionConfig.this);
			// EhCacheUtil cache = EhCacheUtil.getInstance();
			// List<Permission> lst = (List<Permission>)
			// cache.get("requestCache", "permission");
			/*
			 * List<Permission> lst = getPermissions(); for (Permission p : lst)
			 * { System.out.println(p.getModuleName()); for (PermissionItem item
			 * : p.getItems()) { System.out.println(item.getName()); } }
			 */
		} finally {
			/*
			 * 销毁已过期对象
			 */
			factory = null;
			parser = null;
		}
	}

	/*
	 * 读取<xxx>中的值xxx并将其付给qname，通知解析器解析当前节点对应的值。同时对currentValue缓冲器清空，用来保存当前qname对应属性值
	 * 。
	 * 
	 * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
	 * java.lang.String, java.lang.String, org.xml.sax.Attributes)
	 */
	String moduleName = "", moduleValue = "";

	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {

		if ("Permissions".equals(qName)) {
			permissions = new ArrayList<Permission>();
		} else if ("Permission".equals(qName)) {
			permission = new Permission();
			items = new ArrayList<PermissionItem>();
		} else if ("ModuleCode".equals(qName)) {
			moduleName = attributes.getValue("name");
			permission.setModuleName(moduleName);
			moduleValue = attributes.getValue("value");
			permission.setModuleCode(moduleValue);
		} else if ("Item".equals(qName)) {
			permissionItem = new PermissionItem();
			permissionItem.setId(attributes.getValue("id"));
			permissionItem.setModuleValue(moduleValue);
			permissionItem.setModuleName(moduleName);
			permissionItem.setEvent(attributes.getValue("event"));
			permissionItem.setIconCls(attributes.getValue("iconCls"));
			permissionItem.setName(attributes.getValue("name"));
			permissionItem.setPosition(Integer.parseInt(attributes
					.getValue("position")));
			permissionItem
					.setSort(Integer.parseInt(attributes.getValue("sort")));
			permissionItem.setValue(Integer.parseInt(attributes
					.getValue("value")));
			items.add(permissionItem);
		}
		// System.out.println("start:::::" + qName);
	}

	/*
	 * 读取<xxx></xxx>之间的属性值，并将其首先以字符形式保存至字符数组ch中，并记录对应长度，以确保以
	 * length为长度的字符为一个整体，然后讲字符数组中的内容按照length长度为整体加到currentValue缓冲器中
	 * 每次读取xml文件后只会在ch中保存当前所解析到的值，currentValue中也只会有当前的节点所对应的唯一值
	 */
	public void characters(char[] ch, int start, int length)
			throws SAXException {
	}

	/*
	 * 当遇到</xxx>时，将当前的qname，和qname所对应的位于currentValue缓冲器中的值保存到props这个哈希表中去，供外部程序调用
	 * 
	 * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String,
	 * java.lang.String, java.lang.String)
	 */
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// System.out.println("end:::::" + qName);
		if ("Permission".equals(qName)) {
			permission.setItems(items);
			permissions.add(permission);
		} else if ("Permissions".equals(qName)) {
			EhCacheUtil cache = EhCacheUtil.getInstance();
			cache.put(ConstVar.FEREVER_CACHE, "permission", permissions);
		}
	}
}